package pers.zcr.meringue.monolithic.system.captcha.gatewayImpl.hutoolcaptcha;

import cn.hutool.captcha.AbstractCaptcha;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;

public class MathCaptchaGenerator extends CaptchaGenerator {
    public MathCaptchaGenerator(AbstractCaptcha captcha) {
        super(captcha);
    }

    @Override
    String getCode() {
        String code =  captcha.getCode();
        // 去除等号
        code = removeEquals(code);
        // 计算结果
        return evaluateExpression(code);
    }

    //删除字符串中最后的等号
    private String removeEquals(String code) {
        int index = code.lastIndexOf("=");
        if (index != -1) {
            code = code.substring(0, index);
        }
        return code;
    }

    private String evaluateExpression(String expression) {
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression(expression);
        return exp.getValue(String.class);
    }
}
